from flask import render_template, g, redirect, request, jsonify, current_app, session, abort
from info import db, constants
from info.models import User, News, Category
from info.utils.common import query_user_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu


@profile_blu.route('/other_news_list')
def other_news_list():
    """返回指定用户的发布的新闻"""

    # 1. 取参数
    other_id = request.args.get("user_id")
    page = request.args.get("p", 1)

    # 2. 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")

    try:
        paginate = other.news_list.paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route('/other_info')
@query_user_data
def other_info():
    user = g.user
    # 去查询其他人的用户信息
    other_id = request.args.get("user_id")
    if not other_id:
        abort(404)
    # 查询指定id 的用户信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)
    is_followed = False
    # if 当前新闻有作者，并且当前登录用户已经关注这个用户
    if other and user:
        # if user 是否关注过news.user
        if other in user.followed:
            is_followed = True
    data = {
        "is_followed": is_followed,
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "user": g.user.to_dict() if g.user else None
    }

    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow')
@query_user_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 取到当前登录用户
    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }

    return render_template('news/user_follow.html', data=data)


@profile_blu.route("/news_list")
@query_user_data
def news_list():
    """
    用户新闻列表
    :return:
    """
    user = g.user
    # 1.获取页数
    p = request.args.get("p", 1)
    # 2.校验参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    current_page = 1
    total_page = 1
    # 3.查询页数
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 新闻列表对象
        News_list = paginate.items
        # 当前页
        current_page = paginate.page
        # 总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    news_dict_li = []
    for news in News_list:
        news_dict_li.append(news.to_basic_dict())
    data = {"news_list": news_dict_li,
            "total_page": total_page,
            "current_page": current_page}

    return render_template("news/user_news_list.html", data=data)


@profile_blu.route("/news_release", methods=["GET", "POST"])
@query_user_data
def news_release():
    """
    新闻编辑发布
    :return:
    """
    if request.method == "GET":
        # 1.查询新闻分类
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        # 将对象模型列表转化为字典列表
        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())
        # 移除“最新”分类
        category_dict_li.pop(0)
        data = {
            "categories":category_dict_li
        }
        return render_template("news/user_news_release.html", data=data)

    # 1.获取数据
    title = request.form.get("title")
    source = "个人发布"
    category_id = request.form.get("category_id")
    index_image = request.files.get("index_image")
    digest = request.form.get("digest")
    content = request.form.get("content")

    # 2.校验数据
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3.读取上传照片
    try:
        index_image = index_image.read()
    except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 4.创建新闻对象模型
    # 4.1 向七牛云空间上传图片，返回Key
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="数据库查询错误")

    news = News()
    news.title = title
    news.category_id = category_id
    news.index_image = constants.QINIU_DOMIN_PREFIX + key
    news.digest = digest
    news.content = content
    news.user_id = g.user.id
    news.source = source
    # 1代表审核状态
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    return jsonify(errno=RET.OK, errmsg="新闻提交成功，等待审核")


@profile_blu.route('/collection')
@query_user_data
def user_collection():
    """
    分页查询收藏新闻
    :return:
    """
    user = g.user
    # 1.获取页数
    p = request.args.get("p", 1)
    # 2.校验参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    current_page = 1
    total_page = 1
    # 3.查询页数
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 收藏页内容
        collections = paginate.items
        # 当前页
        current_page = paginate.page
        # 总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {"collections": collection_dict_li,
            "total_page": total_page,
            "current_page": current_page}
    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/pass_info", methods=["GET", "POST"])
@query_user_data
def pass_info():
    """
    修改密码
    :return:
    """
    user = g.user
    if request.method == "GET":
        return render_template("news/user_pass_info.html", data={"user": user.to_dict()})
    # 1.获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    # 2.校验参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3.查询密码是否正确
    if not user.check_password(old_password):
        return jsonify(errno=RET.DATAERR, errmsg="原密码错误")
    # 4.更新密码
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg="密码保存失败")
    return jsonify(errno=RET.OK, errmsg="成功")


@profile_blu.route("/pic_info", methods=["GET", "POST"])
@query_user_data
def pic_info():
    """
    上传图片
    :return:
    """
    user = g.user
    if request.method == "GET":
        return render_template("news/user_pic_info.html", data={"user": user.to_dict()})
    # 用户上传图片
    # 1.获取图片
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 2.用自定义方法将文件上传到七牛云，获取key
    try:

        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="数据上传失败")

    # 3.保存key到数据库
    user.avatar_url = key
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    # 4.返回路径
    return jsonify(errno=RET.OK, errmsg="成功", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route("/base_info", methods=["GET", "POST"])
@query_user_data
def base_info():
    """
    获取和修改基本资料,两种请求方式
    :return:
    """
    user = g.user
    # GET请求，获取数据
    if request.method=="GET":
        data = {
            "user_info": user.to_dict()
        }
        return render_template("news/user_base_info.html", data=data)
    # POST请求，代表修改数据
    # 1.获取参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    # 2.校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ["MAN", "WOMEN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3.修改并保存信息
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    # 将session中保存的数据进行实时更新
    session["nick_name"] = nick_name
    return jsonify(errno=RET.OK, errmsg="成功")


@profile_blu.route('/info')
@query_user_data
def user_info():
    """
    个人中心
    :return:
    """
    user = g.user
    if not user:
        # 代表没有值，重定向到首页
        return redirect("/")
    data = {
        "user": user.to_dict()

    }
    return render_template("news/user.html", data=data)